package com.nfc.demo;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class PlacesService
{
	private String API_KEY;

	public PlacesService(String apikey)
	{
		this.API_KEY = apikey;
	}

	public void setApiKey(String apikey)
	{
		this.API_KEY = apikey;
	}

	public ArrayList<Place> getPlaces(double latitude, double longitude, String types, long radius)
	{

		try
		{
			String jsonString = getUrlResults(buildUrl(latitude, longitude, types, radius));

			JSONObject jsonObject = new JSONObject(jsonString);

			JSONArray jsonArray = jsonObject.getJSONArray("results");

			ArrayList<Place> arrayList = new ArrayList<Place>();

			for (int i = 0; i < jsonArray.length(); i++)
			{
				try
				{
					Place place = Place.jsonToPlace((JSONObject) jsonArray.get(i));
					arrayList.add(place);
				}
				catch (Exception e)
				{
					Logger.getLogger(PlacesService.class.getName())
							.log(Level.SEVERE, null, e);
				}
			}

			return arrayList;

		}
		catch (JSONException ex)
		{
			Logger.getLogger(PlacesService.class.getName())
					.log(Level.SEVERE, null, ex);
		}
		return null;
	}

	private String buildUrl(double latitude, double longitude, String types, long radious)
	{
		StringBuilder urlString = new StringBuilder("https://maps.googleapis.com/maps/api/place/search/json?");
		urlString.append("&location=");
		urlString.append(Double.toString(latitude));
		urlString.append(",");
		urlString.append(Double.toString(longitude));
		urlString.append("&radius=" + Long.toString(radious));
		if (!types.equals("")) urlString.append("&types=" + types);
		urlString.append("&sensor=false");
		urlString.append("&key=" + API_KEY);
		return urlString.toString();
	}

	protected String getUrlResults(String urlString)
	{
		StringBuilder content = new StringBuilder();
		try
		{
			URL url = new URL(urlString);
			URLConnection urlConnection = url.openConnection();
			BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));

			String line;
			while ((line = bufferedReader.readLine()) != null)
			{
				content.append(line + "\n");
			}

			bufferedReader.close();
		}
		catch (Exception ex)
		{
			Logger.getLogger(PlacesService.class.getName())
					.log(Level.SEVERE, null, ex);
		}

		return content.toString();
	}
}
